package com.epfresh.api.http;

import android.content.Context;

import com.epfresh.api.http.volley.DefaultRetryPolicy;
import com.epfresh.api.http.volley.Request;
import com.epfresh.api.http.volley.RequestQueue;
import com.epfresh.api.http.volley.RetryPolicy;
import com.epfresh.api.http.volley.toolbox.Volley;
import com.epfresh.api.utils.NetworkUtil;

public class RequestManager {
    private String Tag = "RequestManager";
    private static final String CHARSET_UTF_8 = "UTF-8";

    public static final int TIMEOUT_COUNT = 80 * 1000;

    public static final int RETRY_TIMES = 0;

    private static RequestManager instance = null;
    private RequestQueue mRequestQueue = null;

    private RequestManager() {

    }

    public void init(Context context) {
        this.mRequestQueue = Volley.newRequestQueue(context);
    }

    public static RequestManager getInstance() {
        if (instance == null) {
            synchronized (RequestManager.class) {
                if (instance == null) {
                    instance = new RequestManager();
                }
            }
        }
        return instance;
    }

    public RequestQueue getRequestQueue() {
        return this.mRequestQueue;
    }

    public <T> void request(Request<T> request) {
        mRequestQueue.add(request);
    }

    public void cancel(Object tag) {
        if (tag != null)
        mRequestQueue.cancelAll(tag);
    }

    public void request(Object tag, HttpRequest request) {
        if (request != null) {
            request.onStart(tag);
            RetryPolicy retryPolicy = new DefaultRetryPolicy(TIMEOUT_COUNT, RETRY_TIMES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
            request.setRetryPolicy(retryPolicy);
            request.setTag(tag);
            request(request);


        }
    }

    protected <T> void request(Object data, Object tag, OnRequestListener<T> onRequestListener) {
        HttpRequest request = new HttpRequest(data, onRequestListener);
        request.onStart(tag);
        if (NetworkUtil.isNetworkAvailable()) {
            RetryPolicy retryPolicy = new DefaultRetryPolicy(RequestManager.TIMEOUT_COUNT, RequestManager.RETRY_TIMES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
            request.setRetryPolicy(retryPolicy);
            request.setTag(tag);
        } else {
            request.onFail(HttpRequest.FAIL_NO_NET, null, tag);
        }
        RequestManager.getInstance().request(request);
    }


}
